import router from "@/router";
import { useLoginUserStore } from "@/store/userStore";
import ACCESS_ENUM from "@/access/accsessEnum";
import checkAccess from "@/access/checkAccess";
/**
 * 权限检查
 */
router.beforeEach(async (to, from, next) => {
  //获取当前登录用户
  const loginUserStore = useLoginUserStore();
  let loinUser = loginUserStore.loginUser;

  //如果之前没尝试获取过当前登录的用户信息，才自动登录
  if (!loinUser || !loinUser.userRole) {
    await loginUserStore.fetchLoginUser();
    loinUser = loginUserStore.loginUser;
  }

  //当前页面需要得权限
  const needAccess = (to.meta?.accsee as string) ?? ACCESS_ENUM.NOT_LOGIN;
  //要跳转得页面必须登录
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    if (
      !loinUser ||
      loinUser.userRole === ACCESS_ENUM.NOT_LOGIN ||
      !loinUser.userRole
    ) {
      //跳转到登录页
      next(`/user/login/redirect=${to.fullPath}`);
    }
    //如果用户已经登录了，判断权限是否足够，如果不足则跳转到无权限页面
    if (!checkAccess(loinUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  //放行
  next();
});
